import json
from datetime import datetime
from user import users
from typing import Dict, Any
from aiohttp import web

def get_ws_by_user_id(user_id_to_ws, user_id):
    return user_id_to_ws.get(user_id)

async def handle_private_chat_aiohttp(data, ws, clients, user_id_to_ws):
    sender_info = clients.get(ws)
    if not sender_info:
        print('未找到发送者ws绑定信息')
        return
    sender = sender_info['username']
    receiver_id = data['data'].get('to')
    text = data['data'].get('text')
    if not receiver_id or not text:
        print('缺少receiver_id或text')
        return
    # 查找目标用户信息
    receiver_ws = get_ws_by_user_id(user_id_to_ws, receiver_id)
    receiver_user = None
    for u in users.values():
        if u['id'] == receiver_id:
            receiver_user = u
            break
    if not receiver_user:
        print('目标用户id不在users:', receiver_id)
        return
    msg = {
        'type': 'private_chat',
        'data': {
            'from': sender,
            'to': receiver_user['username'],
            'text': text,
            'timestamp': datetime.now().isoformat(),
            'avatar_color': sender_info.get('avatar_color'),
            'avatar_text': sender_info.get('avatar_text')
        }
    }
    try:
        await ws.send_str(json.dumps(msg, ensure_ascii=False))
        if receiver_ws and receiver_ws != ws:
            await receiver_ws.send_str(json.dumps(msg, ensure_ascii=False))
            print('已推送给对方')
        else:
            print('未推送给对方，ws不存在或是自己')
    except Exception as e:
        print('推送消息异常：', e)
